package com.znz.analysis.mongo;

import java.util.Arrays;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;

/**
 * @author 作者 :TP
 * @version 创建时间：2017年6月22日 上午10:15:13
 *
 */
@Deprecated
public class MongoConnector {
	private MongoDatabase mongoDatabase;
	private MongoClient mongoClient;
	// Singleton
	private volatile static MongoConnector mongoConnector;

	public MongoDatabase getMongoDatabase() {
		return mongoDatabase;
	}

	public void setMongoDatabase(MongoDatabase mongoDatabase) {
		this.mongoDatabase = mongoDatabase;
	}

	public MongoClient getMongoClient() {
		return mongoClient;
	}

	public void setMongoClient(MongoClient mongoClient) {
		this.mongoClient = mongoClient;
	}

	private MongoConnector() {
		init();
	}

	/**
	 * 初始化构造函数时执行
	 */
	private void init() {
		// Mongo认证
		ServerAddress server = new ServerAddress("192.168.2.59", 27017);
		MongoCredential mongoCredential = MongoCredential.createMongoCRCredential("test", "test",
				"test.com".toCharArray());
		MongoClient mongoClient = new MongoClient(server, Arrays.asList(mongoCredential));
		this.setMongoClient(mongoClient);
		// 连接到数据库
		MongoDatabase mongoDatabase = this.getMongoClient().getDatabase("test");
		this.setMongoDatabase(mongoDatabase);
		System.out.println("Connect to database successfully");
	}

	/**
	 * 关闭MongoClient
	 */
	public void close() {
		mongoConnector = null;
		this.getMongoClient().close();
		System.out.println("close the database successfully");
	}

	/**
	 * 获取单例对象
	 * 
	 * @return
	 */
	public static MongoConnector getInstance() {
		// double check
		if (mongoConnector == null) {
			synchronized (MongoConnector.class) {
				if (mongoConnector == null) {
					mongoConnector = new MongoConnector();
				}
			}
		}
		return mongoConnector;
	}

}
